package org.luxor.cloud.authentication.config;

import org.luxor.commons.security.component.ResourceAuthExceptionEntryPoint;
import org.luxor.commons.security.component.RestAccessDeniedHandler;
import org.luxor.commons.security.component.RestBearerTokenExtractor;
import org.luxor.commons.security.config.WebSecurityProperties;
import org.luxor.commons.security.utils.SecurityUtils;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * 资源服务器配置
 *
 * @author Mr.Yan  @date: 2020/9/14
 */
@Order(89)
@Configuration
@EnableResourceServer
public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {

    @Resource
    private ResourceServerProperties resource;
    @Resource
    private TokenStore tokenStore;
    @Resource
    private WebSecurityProperties properties;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(resource.getResourceId())
                .authenticationEntryPoint(new ResourceAuthExceptionEntryPoint())
                .tokenExtractor(new RestBearerTokenExtractor(properties))
                .accessDeniedHandler(new RestAccessDeniedHandler())
                .tokenStore(tokenStore);
    }

    /**
     * 保护作为资源服务器的资源
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.requestMatchers().antMatchers("/system/**","/token/user","/token/removeToken")
                .and().authorizeRequests().anyRequest().authenticated()
                .and().anonymous().principal(SecurityUtils.ANONYMUS)
                .and().csrf().disable();
    }

}
